﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Applica.Models;
using Omu.Drawing;
using System.Drawing;
using System.Web.UI;
namespace Applica.Controllers
{
    public class IphoneController : Controller
    {
        private homewizard_test2databaseEntities db = new homewizard_test2databaseEntities();
        //
        // GET: /Iphone/

        public ActionResult Index()
        {

            //For Testing, we will change it later
            Session["sponsor"] = "Andy";

            SponsorInputs345xModel model = new SponsorInputs345xModel();
            String sponser = Session["sponsor"].ToString().Trim();
            if (!String.IsNullOrEmpty(sponser))
            {

                model = (from s in db.SponsorInputs345x
                         where s.sponsor == sponser
                         select new SponsorInputs345xModel()
                         {
                             Sponsor_ID = s.Sponsor_ID,
                             sponsor = s.sponsor,
                             icompany_name = s.icompany_name,
                             iphone_number = s.iphone_number,
                             iname_line = s.iname_line,
                             imessage_welcome = s.imessage_welcome,
                             imessage_myscreen = s.imessage_myscreen,
                             iemail_address = s.iemail_address,
                             iwebsite = s.iwebsite,
                             ipscountry = s.ips_country,
                             ipsstateprovince = s.ips_state_province,
                             ipromocode = s.ipromocode,
                             ilogo_pic = s.ilogo_pic,
                             ispec_features_msg = s.ispec_features_msg,
                             itagline = s.itagline,
                             icompany_admin_link = s.icompany_admin_link,
                             icon_phone_number = s.icon_phone_number
                             ,
                             icon_email_address = s.icon_email_address,
                             icon_web_address = s.icon_web_address,
                             ifacebook = s.ifacebook,
                             itwitter = s.itwitter
                         }).FirstOrDefault();
                try
                {
                    if (!System.IO.File.Exists(Server.MapPath("~/sponsor_iphone_images/" + model.ilogo_pic)))
                    {
                        model.ilogo_pic = "Default.png";
                    }
                }
                catch { }
                var selectedCountry = "US";
                var selectedState = "";
                if (!String.IsNullOrEmpty(model.ipscountry))
                {
                    selectedCountry = model.ipscountry;
                }
                if (!String.IsNullOrEmpty(model.ipsstateprovince))
                {
                    selectedState = model.ipsstateprovince;
                }

                var location = db.Country_State.Select(e => new { e.country_name, e.country }).Distinct().OrderByDescending(e => e.country_name);
                //ViewBag.Country = new SelectList(location, "country", "country", selectedCountry);

                var state = (from s in db.Country_State
                             where s.country == selectedCountry
                             select s);

                ViewBag.Country = new SelectList(location, "country", "country_name", selectedCountry);

                ViewData["optional"] = "-Select state or region-";

                if (selectedCountry == "CAN")
                {
                    ViewData["optional"] = "-Select Province-";
                }

                if (!String.IsNullOrEmpty(selectedState))
                {
                    ViewBag.State = new SelectList(state, "state_province_code", "state_or_province_name", selectedState);
                }
                else
                {
                    ViewBag.State = new SelectList(state, "state_province_code", "state_or_province_name");
                }

            }
            return View(model);
        }
        public ActionResult banner(SponsorInputs345xModel model)
        {
            Session["sponsor"] = "test";
            String sponser = Session["sponsor"].ToString().Trim();
            model = (from s in db.SponsorInputs345x
                     where s.sponsor == sponser
                     select new SponsorInputs345xModel()
                     {
                         Sponsor_ID = s.Sponsor_ID,
                         sponsor = s.sponsor,
                         icompany_name = s.icompany_name,
                         iphone_number = s.iphone_number,
                         iname_line = s.iname_line,
                         imessage_welcome = s.imessage_welcome,
                         imessage_myscreen = s.imessage_myscreen,
                         iemail_address = s.iemail_address,
                         iwebsite = s.iwebsite,
                         ipscountry = s.ips_country,
                         ipsstateprovince = s.ips_state_province,
                         ipromocode = s.ipromocode,
                         ilogo_pic = s.ilogo_pic,
                         ispec_features_msg = s.ispec_features_msg,
                         itagline = s.itagline,
                         icompany_admin_link = s.icompany_admin_link,
                         icon_phone_number = s.icon_phone_number
                         ,
                         icon_email_address = s.icon_email_address,
                         icon_web_address = s.icon_web_address,
                         ifacebook = s.ifacebook,
                         itwitter = s.itwitter
                     }).FirstOrDefault();

            return PartialView("Custombanner", model);



        }
        public ActionResult Welcom(SponsorInputs345xModel model)
        {
            Session["sponsor"] = "test";
            String sponser = Session["sponsor"].ToString().Trim();
            model = (from s in db.SponsorInputs345x
                     where s.sponsor == sponser
                     select new SponsorInputs345xModel()
                     {
                         Sponsor_ID = s.Sponsor_ID,
                         sponsor = s.sponsor,
                         icompany_name = s.icompany_name,
                         iphone_number = s.iphone_number,
                         iname_line = s.iname_line,
                         imessage_welcome = s.imessage_welcome,
                         imessage_myscreen = s.imessage_myscreen,
                         iemail_address = s.iemail_address,
                         iwebsite = s.iwebsite,
                         ipscountry = s.ips_country,
                         ipsstateprovince = s.ips_state_province,
                         ipromocode = s.ipromocode,
                         ilogo_pic = s.ilogo_pic,
                         ispec_features_msg = s.ispec_features_msg,
                         itagline = s.itagline,
                         icompany_admin_link = s.icompany_admin_link,
                         icon_phone_number = s.icon_phone_number
                         ,
                         icon_email_address = s.icon_email_address,
                         icon_web_address = s.icon_web_address,
                         ifacebook = s.ifacebook,
                         itwitter = s.itwitter
                     }).FirstOrDefault();

            return PartialView("Customwelcome", model);
        }
        public ActionResult Customadmin(SponsorInputs345xModel model)
        {
            Session["sponsor"] = "test";
            String sponser = Session["sponsor"].ToString().Trim();
            model = (from s in db.SponsorInputs345x
                     where s.sponsor == sponser
                     select new SponsorInputs345xModel()
                     {
                         Sponsor_ID = s.Sponsor_ID,
                         sponsor = s.sponsor,
                         icompany_name = s.icompany_name,
                         iphone_number = s.iphone_number,
                         iname_line = s.iname_line,
                         imessage_welcome = s.imessage_welcome,
                         imessage_myscreen = s.imessage_myscreen,
                         iemail_address = s.iemail_address,
                         iwebsite = s.iwebsite,
                         ipscountry = s.ips_country,
                         ipsstateprovince = s.ips_state_province,
                         ipromocode = s.ipromocode,
                         ilogo_pic = s.ilogo_pic,
                         ispec_features_msg = s.ispec_features_msg,
                         itagline = s.itagline,
                         icompany_admin_link = s.icompany_admin_link,
                         icon_phone_number = s.icon_phone_number
                         ,
                         icon_email_address = s.icon_email_address,
                         icon_web_address = s.icon_web_address,
                         ifacebook = s.ifacebook,
                         itwitter = s.itwitter
                     }).FirstOrDefault();

            return PartialView("Customadmin", model);
        }
        public ActionResult Custommyscreen(SponsorInputs345xModel model)
        {
            Session["sponsor"] = "test";
            String sponser = Session["sponsor"].ToString().Trim();
            model = (from s in db.SponsorInputs345x
                     where s.sponsor == sponser
                     select new SponsorInputs345xModel()
                     {
                         Sponsor_ID = s.Sponsor_ID,
                         sponsor = s.sponsor,
                         icompany_name = s.icompany_name,
                         iphone_number = s.iphone_number,
                         iname_line = s.iname_line,
                         imessage_welcome = s.imessage_welcome,
                         imessage_myscreen = s.imessage_myscreen,
                         iemail_address = s.iemail_address,
                         iwebsite = s.iwebsite,
                         ipscountry = s.ips_country,
                         ipsstateprovince = s.ips_state_province,
                         ipromocode = s.ipromocode,
                         ilogo_pic = s.ilogo_pic,
                         ispec_features_msg = s.ispec_features_msg,
                         itagline = s.itagline,
                         icompany_admin_link = s.icompany_admin_link,
                         icon_phone_number = s.icon_phone_number
                         ,
                         icon_email_address = s.icon_email_address,
                         icon_web_address = s.icon_web_address,
                         ifacebook = s.ifacebook,
                         itwitter = s.itwitter
                     }).FirstOrDefault();

            return PartialView("Custommyscreen", model);
        }
        public ActionResult Customsetup(SponsorInputs345xModel model)
        {
            Session["sponsor"] = "test";
            String sponser = Session["sponsor"].ToString().Trim();
            model = (from s in db.SponsorInputs345x
                     where s.sponsor == sponser
                     select new SponsorInputs345xModel()
                     {
                         Sponsor_ID = s.Sponsor_ID,
                         sponsor = s.sponsor,
                         icompany_name = s.icompany_name,
                         iphone_number = s.iphone_number,
                         iname_line = s.iname_line,
                         imessage_welcome = s.imessage_welcome,
                         imessage_myscreen = s.imessage_myscreen,
                         iemail_address = s.iemail_address,
                         iwebsite = s.iwebsite,
                         ipscountry = s.ips_country,
                         ipsstateprovince = s.ips_state_province,
                         ipromocode = s.ipromocode,
                         ilogo_pic = s.ilogo_pic,
                         ispec_features_msg = s.ispec_features_msg,
                         itagline = s.itagline,
                         icompany_admin_link = s.icompany_admin_link,
                         icon_phone_number = s.icon_phone_number
                         ,
                         icon_email_address = s.icon_email_address,
                         icon_web_address = s.icon_web_address,
                         ifacebook = s.ifacebook,
                         itwitter = s.itwitter
                     }).FirstOrDefault();

            return PartialView("Customsetup", model);
        }
        public ActionResult Customlocation(SponsorInputs345xModel model)
        {
            Session["sponsor"] = "test";
            String sponser = Session["sponsor"].ToString().Trim();
            model = (from s in db.SponsorInputs345x
                     where s.sponsor == sponser
                     select new SponsorInputs345xModel()
                     {
                         Sponsor_ID = s.Sponsor_ID,
                         sponsor = s.sponsor,
                         icompany_name = s.icompany_name,
                         iphone_number = s.iphone_number,
                         iname_line = s.iname_line,
                         imessage_welcome = s.imessage_welcome,
                         imessage_myscreen = s.imessage_myscreen,
                         iemail_address = s.iemail_address,
                         iwebsite = s.iwebsite,
                         ipscountry = s.ips_country,
                         ipsstateprovince = s.ips_state_province,
                         ipromocode = s.ipromocode,
                         ilogo_pic = s.ilogo_pic,
                         ispec_features_msg = s.ispec_features_msg,
                         itagline = s.itagline,
                         icompany_admin_link = s.icompany_admin_link,
                         icon_phone_number = s.icon_phone_number
                         ,
                         icon_email_address = s.icon_email_address,
                         icon_web_address = s.icon_web_address,
                         ifacebook = s.ifacebook,
                         itwitter = s.itwitter
                     }).FirstOrDefault();

            return PartialView("Customlocation", model);
        }
        public JsonResult Update(SponsorInputs345xModel model)
        {

            try
            {

                var sponser = (from s in db.SponsorInputs345x
                               where s.sponsor == model.sponsor
                               select s).First();
                if (!String.IsNullOrEmpty(model.icompany_name))
                {
                    sponser.icompany_name = model.icompany_name;
                }
                if (!String.IsNullOrEmpty(model.iphone_number))
                {
                    sponser.iphone_number = model.iphone_number;
                }
                if (!String.IsNullOrEmpty(model.iname_line))
                {
                    sponser.iname_line = model.iname_line;
                }

                if (!String.IsNullOrEmpty(model.imessage_welcome))
                {
                    sponser.imessage_welcome = model.imessage_welcome;
                }
                if (!String.IsNullOrEmpty(model.imessage_myscreen))
                {
                    sponser.imessage_myscreen = model.imessage_myscreen;
                }

                if (!String.IsNullOrEmpty(model.iemail_address))
                {
                    sponser.iemail_address = model.iemail_address;
                }

                if (!String.IsNullOrEmpty(model.iwebsite))
                {
                    sponser.iwebsite = model.iwebsite;
                }
                if (!String.IsNullOrEmpty(model.ipscountry))
                {
                    sponser.ips_country = model.ipscountry;
                }
                if (!String.IsNullOrEmpty(model.ipsstateprovince))
                {
                    sponser.ips_state_province = model.ipsstateprovince;
                }
                if (!String.IsNullOrEmpty(model.ipromocode))
                {
                    sponser.ipromocode = model.ipromocode;
                }
                if (!String.IsNullOrEmpty(model.ispec_features_msg))
                {
                    sponser.ispec_features_msg = model.ispec_features_msg;
                }
                if (!String.IsNullOrEmpty(model.itagline))
                {
                    sponser.itagline = model.itagline;
                }
                if (!String.IsNullOrEmpty(model.icompany_admin_link))
                {
                    sponser.icompany_admin_link = model.icompany_admin_link;
                }



                if (!String.IsNullOrEmpty(model.icon_phone_number))
                {
                    sponser.icon_phone_number = model.icon_phone_number;
                }
                if (!String.IsNullOrEmpty(model.icon_email_address))
                {
                    sponser.icon_email_address = model.icon_email_address;
                }
                if (!String.IsNullOrEmpty(model.icon_web_address))
                {
                    sponser.icon_web_address = model.icon_web_address;
                }
                if (!String.IsNullOrEmpty(model.ifacebook))
                {
                    sponser.ifacebook = model.ifacebook;
                }
                if (!String.IsNullOrEmpty(model.itwitter))
                {
                    sponser.itwitter = model.itwitter;
                }

                if (ModelState.IsValid)
                {
                    db.SponsorInputs345x.ApplyCurrentValues(sponser);
                    db.SaveChanges();
                }
                return Json(new { success = "<span style='color:green;' >Your changes have been saved.</span>" });
            }
            catch
            {
                return Json(new { success = "<span style='color:red;' >Some error occured.</span>" });
            }

        }

        //public ActionResult UpdatewithImage(SponsorInputs345xModel model)
        //{

        //    try
        //    {


        //        var sponser = (from s in db.SponsorInputs345x
        //                       where s.sponsor == model.sponsor
        //                       select s).First();
        //        if (!String.IsNullOrEmpty(model.icompany_name))
        //        {
        //            sponser.icompany_name = model.icompany_name;
        //        }
        //        if (!String.IsNullOrEmpty(model.iphone_number))
        //        {
        //            sponser.iphone_number = model.iphone_number;
        //        }
        //        if (!String.IsNullOrEmpty(model.iname_line))
        //        {
        //            sponser.iname_line = model.iname_line;
        //        }

        //        if (!String.IsNullOrEmpty(model.imessage_welcome))
        //        {
        //            sponser.imessage_welcome = model.imessage_welcome;
        //        }
        //        if (!String.IsNullOrEmpty(model.imessage_myscreen))
        //        {
        //            sponser.imessage_myscreen = model.imessage_myscreen;
        //        }

        //        if (!String.IsNullOrEmpty(model.iemail_address))
        //        {
        //            sponser.iemail_address = model.iemail_address;
        //        }

        //        if (!String.IsNullOrEmpty(model.iwebsite))
        //        {
        //            sponser.iwebsite = model.iwebsite;
        //        }
        //        if (!String.IsNullOrEmpty(model.ipscountry))
        //        {
        //            sponser.ips_country = model.ipscountry;
        //        }
        //        if (!String.IsNullOrEmpty(model.ipsstateprovince))
        //        {
        //            sponser.ips_state_province = model.ipsstateprovince;
        //        }
        //        if (!String.IsNullOrEmpty(model.ipromocode))
        //        {
        //            sponser.ipromocode = model.ipromocode;
        //        }


        //        //File Upload Start
        //        var file = Request.Files[0];
        //        if (file != null && file.ContentLength > 0)
        //        {
        //            var fileName = Path.GetFileName(file.FileName);
        //            //var finalfilename = model.Sponsor_ID + "iphone_image";
        //            var path = Path.Combine(Server.MapPath("~/sponser_iphone_images/"), fileName);
        //            file.SaveAs(path);
        //            sponser.ilogo_pic = fileName;


        //            //Create Cookie to Retain Tab of This
        //            //HttpCookie myCookie = new HttpCookie("Tabs");
        //            //DateTime now = DateTime.Now;
        //            // Set the cookie value.
        //            //myCookie.Value = "1";
        //            // Set the cookie expiration date.
        //            //myCookie.Expires = now.AddMinutes(60);
        //            // Add the cookie.
        //            //Response.Cookies.Add(myCookie);


        //        }
        //        //File Upload End

        //        if (ModelState.IsValid)
        //        {
        //            db.SponsorInputs345x.ApplyCurrentValues(sponser);
        //            db.SaveChanges();
        //        }
        //        return RedirectToAction("Index");
        //        //return Json(new { success = "<span style='color:green;' >Your changes have been saved.</span>" });
        //    }
        //    catch
        //    {
        //        return RedirectToAction("Index");
        //        //return Json(new { success = "<span style='color:red;' >Some error occured.</span>" });
        //    }

        //}

        [HttpGet]
        public ActionResult getStatesbyCountry(string country)
        {
            //perform your action here
            var states = (from s in db.Country_State
                          where s.country == country
                          select s).ToList();
            var result = (from s in states
                          select new { id = s.state_province_code, name = s.state_or_province_name })
                          .ToList();

            return Json(result, JsonRequestBehavior.AllowGet);
        }


        //[HttpPost]
        //public ContentResult UploadFiles(string id)
        //{

        //    var r = new List<UploadFilesResult>();
        //    SponsorInputs345xModel model = new SponsorInputs345xModel();
        //    model.Sponsor_ID = Convert.ToInt32(id);
        //    foreach (string file in Request.Files)
        //    {
        //        HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
        //        if (hpf.ContentLength == 0)
        //            continue;
        //        string savedFileName = Path.Combine(Server.MapPath("~/sponser_iphone_images"), Path.GetFileName(hpf.FileName));
        //        //Rename Image

        //        string extension = Path.GetExtension(hpf.FileName);
        //        string newname = id + "_" + "iphone_image" + extension;
        //        savedFileName = Path.Combine(Server.MapPath("~/sponser_iphone_images"), newname);

        //        hpf.SaveAs(savedFileName);

        //        r.Add(new UploadFilesResult()
        //        {
        //            Name = hpf.FileName,
        //            Length = hpf.ContentLength,
        //            Type = hpf.ContentType,
        //            ImagePath = savedFileName
        //        });

        //        Int32 id_ = Convert.ToInt32(id);
        //        var sponser = (from s in db.SponsorInputs345x
        //                       where s.Sponsor_ID == id_
        //                       select s).First();
        //        sponser.ilogo_pic = newname;

        //        if (ModelState.IsValid)
        //        {
        //            db.SponsorInputs345x.ApplyCurrentValues(sponser);
        //            db.SaveChanges();
        //        }


        //    }


        //    return Content("{\"name\":\"" + r[0].Name + "\",\"type\":\"" + r[0].Type + "\",\"imagepath\":\"" + r[0].ImagePath + "\",\"size\":\"" + string.Format("{0} bytes", r[0].Length) + "\"}", "application/json");
        //}

        [HttpPost]

        public ContentResult UploadFiles(string id)
        {
            decimal Lx = 125;
            decimal Ly = 121;
            decimal L2;
            decimal newWidth = 125, newHeight = 122;
            var r = new List<UploadFilesResult>();
            SponsorInputs345xModel model = new SponsorInputs345xModel();
            model.Sponsor_ID = Convert.ToInt32(id);
            foreach (string file in Request.Files)
            {
                Int32 id_ = Convert.ToInt32(id);
                var sponser = (from s in db.SponsorInputs345x
                               where s.Sponsor_ID == id_
                               select s).First();
                HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                if (hpf.ContentLength == 0)
                    continue;
                Image originalImg = System.Drawing.Image.FromStream(hpf.InputStream);
                if (originalImg.Width > originalImg.Height)
                {
                    decimal ratio = Convert.ToDecimal(originalImg.Width) / Convert.ToDecimal(originalImg.Height);
                    newWidth = ratio * 122;



                }
                else
                {
                    decimal ratio = Convert.ToDecimal(originalImg.Height) / Convert.ToDecimal(originalImg.Width);
                    newHeight = ratio * 125;

                }




                string savedFileName = Path.Combine(Server.MapPath("~/Temp"), Path.GetFileName(hpf.FileName));
                //Rename Image
                string newname = "";

                string extension = Path.GetExtension(hpf.FileName);
                if (sponser.ilogo_pic.Contains("-1"))
                {
                    newname = id + "_" + "iphone_image" + extension;
                }
                else
                {
                    newname = id + "_" + "iphone_image-1" + extension;
                }
                savedFileName = Path.Combine(Server.MapPath("~/Temp"), newname);

                hpf.SaveAs(savedFileName);

                r.Add(new UploadFilesResult()
                {
                    Name = hpf.FileName,
                    Length = hpf.ContentLength,
                    Type = hpf.ContentType,
                    ImagePath = newname
                });


                sponser.ilogo_pic = newname;

                if (ModelState.IsValid)
                {
                    db.SponsorInputs345x.ApplyCurrentValues(sponser);
                    db.SaveChanges();
                    db.Dispose();
                }


                using (var image = Image.FromFile(savedFileName))
                {
                    int x = 0;
                    int y = 0;
                    if (Convert.ToInt32(newWidth) > 125)
                    {
                        x = Convert.ToInt32(newWidth) - 125;
                        x = x / 2;
                    }
                    else
                    {
                        y = Convert.ToInt32(newHeight) - 121;
                        y = y / 2;
                    }
                    //var img = Imager.Crop(image, new Rectangle(0, 0, Convert.ToInt32(newWidth), Convert.ToInt32(newHeight)));
                    Image resized = Imager.Resize(image, Convert.ToInt32(newWidth), Convert.ToInt32(newHeight), true);


                    // var img = Imager.Crop(resized, new Rectangle(x, y, 125, 121));
                    Imager.SaveJpeg(Path.Combine(Server.MapPath("~/sponsor_iphone_images"), newname), resized);
                }



                // System.IO.File.Delete(savedFileName);
            } //,\"path\":\"" + r[0].ImagePath + "\"
            return Content("{\"name\":\"" + r[0].Name + "\",\"path\":\"" + r[0].ImagePath + "\",\"type\":\"" + r[0].Type + "\",\"size\":\"" + string.Format("{0} bytes", r[0].Length) + "\"}", "application/json");

        }
        [HttpPost]
        public ContentResult restoreFile(SponsorInputs345xModel model)
        {
            Int32 id_ = Convert.ToInt32(model.Sponsor_ID);
            var sponser = (from s in db.SponsorInputs345x
                           where s.Sponsor_ID == id_
                           select s).First();
            sponser.ilogo_pic = "Default.png";
            var image = sponser.ilogo_pic;
            if (ModelState.IsValid)
            {
                db.SponsorInputs345x.ApplyCurrentValues(sponser);
                db.SaveChanges();
                db.Dispose();
            }
            return Content("{\"name\":\"" + image + "\"}", "application/json");
        }

    }
}
